<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title>C++ Tutorial: Object Returning</title>
  <meta
 content="C++ Tutorial: Object Returning"
 name="description" />
  <meta
 content="C++ Tutorial, Object Returning, Reference, const Object"
 name="keywords" />
  <meta http-equiv="Content-Type"
 content="text/html; charset=ISO-8859-1" />
  <link type="text/css" rel="stylesheet" href="../images/bogostyleWidePre.css" />
</head>
<body>
<div id="page" align="center">
<div id="content" style="width: 800px;">
<div id="logo">
<div class="whitetitle" style="margin-top: 70px;">bogotobogo </div>
</div>
<div id="topheader">
<div class="headerbodytext" align="left"><br />
<strong>Bogotobogo</strong><br />
contact@bogotobogo.com </div>
<div class="smallgraytext" id="toplinks"><a href="../index.html">Home</a>
| <a href="../sitemap.html">Sitemap</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="menu">
<div class="smallwhitetext" style="padding: 9px;" align="right"><a
 href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">Products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="../blog" target="_blank">Contact Us</a>
</div>
</div>
<div id="submenu">
<div class="smallgraytext" style="padding: 9px;" align="right">
<a href="../gif.html">Gif</a> 
|<a href="../java_applet.html">JavaApplet/Web Start</a>
| <a href="../flash.html">Flash</a>
| <a href="../shockwave.html">ShockWave</a>
| <a href="../svg.html">SVG</a>
| <a href="../iPhone.html">iPhone/iPad</a>
| <a href="../android.html">Android</a>
| <a href="../OnHTML5.html">HTML5</a>
| <a href="../Algorithms/algorithms.html">Algorithms</a>
| <a href="../News/NewsMain.html">News</a>
| <a href="../cplusplus/cpptut.html">C++</a>
| <a href="../Java/tutorial/on_java.html">Java</a>
| <a href="../php/phptut.html">PHP</a>
| <a href="../DesignPatterns/introduction.html">Design Patterns</a>
| <a href="../python/pytut.html">Python</a> 
| <a href="../CSharp/.netframework.html">C#</a>
| <a href="../forums.html">Forums</a> 
| <a href="../VisualBasicSQL/introduction.html">Visual Basic</a>
</div>
</div>

<div id="contenttext">

<!-- Use of this code assumes agreement with the Google Custom Search Terms of Service. -->
<!-- The terms of service are available at http://www.google.com/cse/docs/tos.html -->
<form name="cse" id="searchbox_demo" action="http://www.google.com/cse">
  <input type="hidden" name="cref" value="" />
  <input type="hidden" name="ie" value="utf-8" />
  <input type="hidden" name="hl" value="" />
  <input name="q" type="text" size="40" />
  <input type="submit" name="sa" value="Search" />
</form>
<script type="text/javascript" src="http://www.google.com/cse/tools/onthefly?form=searchbox_demo&lang="></script>

<div id="bookmarkshare">
<script type="text/javascript">var addthis_config = {"data_track_clickback":true};</script>
<a class="addthis_button" href="http://www.addthis.com/bookmark.php?v=250&amp;username=khhong7"><img src="http://s7.addthis.com/static/btn/v2/lg-share-en.gif" width="125" height="16" alt="Bookmark and Share" style="border:0"/></a><script type="text/javascript" src="http://s7.addthis.com/js/250/addthis_widget.js#username=khhong7"></script>
</div>
<br />
<br />
<br />
<br />
<div style="padding: 10px;"><span class="titletext">C++ Tutorial - Object Returning</span></div>
<img src="../images/cplusplus/cpp_logo.jpg" alt="cplusplus logo"/>

<div class="bodytext" style="padding: 12px;" align="justify"> 
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>   
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors (Function Objects)</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="stl3_iterators.html">Standard Template Library (STL) III - Iterators</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
</div>
<br />

<br /><br />
<img src="images/objectreturning/DahlMahSan.png" alt="DahlMahSan"/>
<br /><br />


<div class="bodytext" style="padding: 12px;" align="justify">
<div class="subtitle" id="objectreturning">Object Returning</div>
<p>When a function either a member function or a standalone function returns an object, we have choices. The function could return</p>
<ul>
	<li>A reference to an object </li>
	<li>A constant reference to an object </li>
	<li>An object</li>
	<li>A constant object</li>
</ul>
<br />
<br />


<div class="subtitle_2nd" id="reftoconstobj">Returning a Reference to a const object</div>
<p>Though the main reason for using <strong>const</strong> reference is efficiency, there are restrictions on when this choice could be used. If a function returns an object that is passed to it, either by object invocation or as a method argument, we can increase the efficiency of the method by having it pass a <strong>reference</strong>.</p>
<p>For example, suppose we want to write a function Maximum() that returns the larger of two <strong>Complx</strong> objects, where the <strong>Complx</strong> is defined as below.</p>
<pre>
#include &lt;iostream&gt;
#include &lt;cmath&gt;

using namespace std;

class Complx {
private:
	double real;
	double imag;
public:
	Complx() {}
	Complx(double r, double i): real(r), imag(i) {}
	Complx  operator+(const Complx & c) const {
		return Complx(real + c.real, imag + c.imag);
	}
	Complx & operator=(const Complx &c) {
		real = c.real;
		imag = c.imag;
		return *this;
	}

	friend ostream& operator<<(ostream &os, const Complx &c);
	double size() const {
		return sqrt(real*real + imag*imag);
	}
};

ostream & operator<<(ostream &os, const Complx & c) {
	os << "(" << c.real << "," << c.imag << ")";
	return os;
}

/*
Complx Maximum(const Complx &c1, const Complx &c2) {
	
	if (c1.size() > c2.size()) 
		return c1;
	else
		return c2;
}
*/

const Complx & Maximum(const Complx &c1, const Complx &c2) {
	
	if (c1.size() > c2.size()) 
		return c1;
	else
		return c2;
}

int main( ) 
{ 
	Complx c1(10,30);
	Complx c2(13,25);
	Complx mx = Maximum (c1,c2);

	cout << " c1 = " << c1 << endl;
	cout << " c2 = " << c2 << endl;
	cout << "Maximum(c1,c2) = " << mx << endl;

	Complx c3 (20,40);
	Complx c4,c5;
	c5 = c4 = c3;

	cout << c4 << " got its value from c3" << endl;

	Complx c6 = c1 + c2;
	cout << " c6 (c1+c2) = " << c6 << endl;

	Complx c7;
	c1 + c2 = c7;
	return 0; 
}
</pre>
<p>Output is: </p>
<pre>
 c1 = (10,30)
 c2 = (13,25)
Maximum(c1,c2) = (10,30)
(20,40) got its value from c3
 c6 (c1+c2) = (23,55)
</pre>
<br />
<p>Either of the following two implementations for <strong>Maximum()</strong> would work:</p>
<pre>
// version #1
Complx Maximum(const Complx &c1, const Complx &c2) {
	
	if (c1.size() > c2.size()) 
		return c1;
	else
		return c2;
}

// version #2 : <font color="red">This is our choice </font>
const Complx & Maximum(const Complx &c1, const Complx &c2) {
	
	if (c1.size() > c2.size()) 
		return c1;
	else
		return c2;
}
</pre>
<p>There are three points that can be emphasized:</p>
<ol>
	<li>Returning an object invokes the <strong>copy constructor</strong> while returning a reference doesn't. So, the version #2 does less work and is more efficient.</li>
	<li>The reference should be to an object that exists when the calling function is execution. In this example, the reference is to either <strong>c1</strong> or <strong>c2</strong>, and both are objects defined in the calling function, so the requirement is met.</li>
	<li>Both <strong>c1</strong> or <strong>c2</strong> are declared as being const references, so the return type has to be <strong>const</strong> to match.</li>
</ol>
<br />
<br />


<div class="subtitle_2nd" id="reftononconstobj">Returning a Reference to a Non-const Object</div>
<p>There are two common examples of returning a <strong>non-const</strong> object</p>
<ul>
	<li>Overloading the assignment operator</li>
	<li>Overloading the << operator for use with <strong>cout</strong></li>
</ul>
<p>The return value of <strong>operator==()</strong> is used for chained assignment:</p>
<pre>
Complx c3 (20,40);
Complx c4,c5;
c5 = c4 = c3;
</pre>
In the code, the return value of <strong>c4.operator=(c3)</strong> is assigned to <strong>c5</strong>. Returning either a <strong>Complx</strong> object or a reference to a <strong>Complx</strong> object would work. But using a reference allows the function to avoid calling the <strong>Complx</strong> copy constructor to create a new <strong>Complx</strong> object. In this case, the return type is not <strong>const</strong> because <strong>operator=()</strong> method returns a reference to <strong>c4</strong>, which is does modify.</p>
<p>The return value of <strong>operator<<()</strong> is used for chained output:</p>
<pre>
cout << c4 << " got its value from c3" << endl;
</pre>
<p>In the code, the return value of <strong>operator<<(cout,c4)</strong> becomes the object used to display the string " got its value from c3". Here, the return type must be <strong>ostream &amp;</strong>  and not just <strong>ostream</strong>. Using an <strong>ostream</strong> return type would require calling the <strong>ostream</strong> copy constructor, and, as it turns out the <strong>ostream</strong> class does not have a public copy constructor. Fortunately, returning a reference to <strong>cout</strong> poses no problems because <strong>cout</strong> is already in scope of the calling function.</p>
<br />
<br />


<div class="subtitle_2nd" id="anobject">Returning a Non-const Object</div>
<p>If the object being returned is <strong>local</strong> to the called function, then it <strong>should not be returned by reference</strong> because the local object has its destructor called when the function terminates. So, when control returns to the calling function, there is no object left to which the reference can refer. In these circumstances, we should return an object, not a reference. <strong>Never Retrun a reference to a local object</strong>. </p>
<p>For example, assume we have a function returning a local object like this:</p>
<pre>
const Complx &complxReturn(const Complx & c) {
		Complx complxObj = c;
		return complxObj;
}
</pre>
<p>When the conction completes, the storage in which the local objects were allocated is freed. A reference to a local object refers to undefined memory after the function terminates. So, the function may fail at run time because it returns a reference to a local object. Whe functions ends, the storage in which <strong>complxObj</strong> resides is freed. The return value refers to memory that is no longer available to the program.</p>
<p>Usually, overloaded arithmetic operators fall into this category. In our example, we have overloaded <strong>operator+</strong>: </p>
<pre>
Complx  operator+(const Complx & c) const {
	return Complx(real + c.real, imag + c.imag);
}
</pre>
<p>When we do</p>
<pre>
Complx c6 = c1 + c2;
</pre>
<p>The value being returned is not <strong>c1</strong>, which should be left unchanged by the process, nor <strong>c2</strong>, which should also be unaltered. Thus the return value can't be a reference to an object that is already present in the calling function. Instead, the sum is a new, temporary object computed from <strong>Complx operator+()</strong>, and the function shouldn't return a reference to a temporary object, either. Instead, it should return an <strong>actual object</strong>, not a reference:</p>
<pre>
Complx  operator+(const Complx & c) const {
	return Complx(real + c.real, imag + c.imag);
}
</pre>
<p>There is the added expense of calling the copy constructor to create the returned object, but that's unavoidable.</p>
<br />
<br />


<div class="subtitle_2nd" id="aconstobject">Returning a const Object</div>
<p>The <strong>Complx::operator+()</strong> in the example has a strange property. The intended use is this:</p>
<pre>
Complx c6 = c1 + c2;	// #1
</pre>
<p>But the definition also allows us to use the following:</p>
<pre>
Complx c7;
c1 + c2 = c7;	// #2
</pre>
<p>This code is possible because the copy constructor constructs a temporary object to represent the return value. So, in the code, the expression <strong>c1 + c2</strong> stands for that temporary object. In statement #1, the temporary object is assigned to <strong>c6</strong>. In statement #2, <strong>c7</strong> is assigned to the temporary object.</p>
<p>The temporary object is used and then discarded. For instance, in statement #2, the program computes the sum of <strong>c1</strong> and <strong>c2</strong>, copies the answer into the temporary return object, overwrites the contents with the contents of <strong>c7</strong>, and then discards the temporary object. The original complex numbers are all left unchanged.</p>
<p>If we declare the return type as a <strong>const</strong> object, we can avoid the problem.</p>
<pre>
<font color="red">const</font> Complx  operator+(const Complx & c) const {
	return Complx(real + c.real, imag + c.imag);
}
</pre>

<br />
<br />


<div class="subtitle_2nd" id="summary">Summary</div>
<ol>
	<li>If a method or function returns a local object, it should return an object, not a reference.</li>
	<li>If a method or function returns an object of a class for which there is no public copy constructor, such as <strong>ostream</strong> class, it must return a reference to an object.</li>
	<li>Some methods and functions, such as the overloaded assignment operator, can return either an object or a reference to an object. The reference is preferred for reasons of efficiency.</li>
        <li>It is an error to return a pointer to a local object. Once the function completes, the local object are freed. The pointer would be a <strong>dangling pointer</strong> that refers to a nonexistent object.</li>
</ol>

<br /><br />
<img src="images/objectreturning/DahlMahSan2.png" alt="DahlMahSan2"/>
<br /><br />

<br /><br />
<div class="subtitle_2nd" id="FullList">Full List of C++ Tutorials</div>
<ul>
   <li><a href="cpptut.html">C++ Home</a> </li>
   <li><a href="string.html">String</a> </li>
   <li><a href="constructor.html">Constructor</a> </li>
   <li><a href="operatoroverloading.html">Operator Overloading</a> </li>
   <li><a href="virtualfunctions.html">Virtual Functions</a></li>
   <li><a href="dynamic_cast.html">Dynamic Cast Operator</a></li>
   <li><a href="typecast.html">Type Cast Operators</a></li>
   <li><a href="autoptr.html">Class auto_ptr</a></li>
   <li><a href="templates.html">Templates</a></li>
   <li><a href="references.html">References for Built-in Types</a></li>
   <li><a href="valuevsreference.html">Pass by Value vs. Pass by Reference</a></li>
   <li><a href="memoryallocation.html">Memory Allocation</a></li>
   <li><a href="friendclass.html">Friend Functions and Friend Classes</a></li>
   <li><a href="functors.html">Functors</a></li>
   <li><a href="statics.html">Static Variables and Static Class Members</a></li>
   <li><a href="exceptions.html">Exceptions</a></li>
   <li><a href="pointers.html">Pointers</a></li>
   <li><a href="pointers2.html">Pointers II</a></li>
   <li><a href="pointers3.html">Pointers III</a></li>
   <li><a href="assembly.html">Taste of Assembly</a></li>
   <li><a href="smallprograms.html">Small Programs</a></li>
   <li><a href="linkedlist.html">Linked List Examples</a></li>
   <li><a href="binarytree.html">Binary Tree Example Code</a></li>
   <li><a href="stl.html">Standard Template Library (STL) I</a></li>
   <li><a href="stl2.html">Standard Template Library (STL) II - Maps</a></li>
   <li><a href="slicing.html">Object Slicing and Virtual Table</a></li>
   <li><a href="this_pointer.html">The this Pointer</a></li>
   <li><a href="stackunwinding.html">Stack Unwinding</a></li>
   <li><a href="upcasting_downcasting.html">Upcasting and Downcasting</a></li>
   <li><a href="object_returning.html">Object Returning</a></li>
   <li><a href="private_inheritance.html">Private Inheritance</a></li>
   <li><a href="cplusplus_keywords.html">C++_Keywords</a></li>
   <li><a href="multithreaded.html">Multi-Threaded Programming - Terminology</a></li>
   <li><a href="multithreaded2A.html">Multi-Threaded Programming II - Native Thread for Win32 (A) </a></li>
   <li><a href="multithreaded2B.html">Multi-Threaded Programming II -  Native Thread for Win32 (B) </a></li>
   <li><a href="multithreaded2C.html">Multi-Threaded Programming II -  Native Thread for Win32 (C) </a></li>
   <li><a href="multithreaded2.html">Multi-Threaded Programming II - C++ Thread for Win32</a></li>
   <li><a href="multithreaded3.html">Multi-Threaded Programming III - C++ Class Thread for Pthreads</a></li>   
   <li><a href="multithreadedDebugging.html">Multithread Debugging</a></li>
   <li><a href="embeddedSystemsProgramming.html">Embedded Systems Programming</a></li>
   <li><a href="boost.html">Boost</a></li>
   <li>Programming Questions and Solutions
    <ul>
       <li><a href="quiz_strings_arrays.html">Strings and Arrays</a></li>
       <li><a href="quiz_linkedlist.html">Linked List</a></li>
       <li><a href="quiz_recursion.html">Recursion</a></li>
       <li><a href="quiz_bit_manipulation.html">Bit Manipulation</a> </li>
       <li><a href="google_interview_questions.html">140 Google Interview Questions</a> </li>
    </ul>
   </li>
</ul>
<br /><br />



<br />


<br />
<br />
<br />


</div>
</div>
<div class="smallgraytext" id="footer"><a href="../index.html">Home</a>
| <a href="../about_us.html">About Us</a>
| <a href="../products.html">products</a>
| <a href="../our_services.html">Our Services</a>
| <a href="#">Contact Us</a>
| Bogotobogo &copy; 2011 | <a target="_blank" href="http://www.bogotobogo.com">Bogotobogo </a>
</div>
</div>
</div>
</body>
</html>
